package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.common.R;
import com.example.demo.common.S;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import com.example.demo.utils.SMSUtils;
import com.example.demo.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

//pvvdoxhrblpydihj
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    //发送QQ验证码
    @GetMapping("/sendMsg/{phone}")
    public S<String> sendMsg(@PathVariable String phone, HttpSession httpSession){
        //获取QQ邮箱
        User user=new User();
        user.setPhone(phone);
        String Emil=user.getPhone();
        log.info("获取的QQ号"+Emil);
        if (StringUtils.isNotEmpty(Emil)){
        //生成随机的4为验证码
            String s = ValidateCodeUtils.achieveCode();
            log.info("获取的验证码"+s);
            //调用QQ提供的邮箱服务发送验证码
            SMSUtils.sendAuthCodeEmail(Emil,s);
        //需要将生成的验证码保存到Session
            httpSession.setAttribute(Emil,s);
            return S.success("QQ邮箱验证码发送成功");
            }
       return S.error("验证码发送失败");
    }
    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(String.valueOf(map));
        //获取手机号

        String phone1 = map.get("phone").toString();
        //获取验证码
        String code = map.get("code").toString();
        //聪session获取保存的验证码
        String s = session.getAttribute(phone1).toString();
        //进行验证码的比对（页面提交的验证码和sessiond的验证码比较）
        if(s!=null&&s.equals(code)){
            //如果对比成功，说明登录成功
            //判断当前是否为新用户，如果是，就直接注册
//            LambdaQueryWrapper<User> lambdaQueryWrapper=new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(User::getPhone,phone1);
            //User user = userService.getOne(lambdaQueryWrapper);
            User user = userService.getbyphone(phone1);
            if(user==null){
                 user=new User();
                user.setPhone(phone1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }

        return R.error("失败");
    }
}
